﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace MvePublicService.ClipOperations
{
	/*
	 * 日本SGI株式会社
	 * ヨハンソン・ヘンリク
	 * johansson@sgi.co.jp
	 * 
	 * Change Log:
	 * ---------------------------------------------------------------------------
	 * 2009.01.07	Johansson Henrik		Class Created.
	 * 
	 */

	/// <summary>
	/// Helper class to create Objects from Clip entries in the Database.
	/// Use this class to Load Clips from the Databse.
	/// </summary>
	/// <example>Clip clip = LoadClipFromDatabase(1, sqlConnection);</example>
	/// <seealso cref="Clip"/>
	/// <remarks>INSERT:Creds</remarks>
	internal static class ClipLoader
	{
		/// <summary>
		/// Loads a single Clip from the DB into a Clip object.
		/// Requires that no other commands are open on the connection used to fetch the Clip.
		/// </summary>
		/// <param name="clipId">Id of Clip to load</param>
		/// <param name="connection">Sql Connection</param>
		/// <returns>Oject Representation of the loaded Clip.</returns>
		internal static Clip LoadClipFromDatabase(int clipId, SqlConnection connection)
		{
			SqlCommand command = new SqlCommand();
			SqlDataReader reader = null;
			command.CommandTimeout = 60;

			Clip result = null;

			try
			{
				command.Connection = connection;
				command.CommandType = System.Data.CommandType.StoredProcedure;
				command.CommandText = "GetClip";
				command.Parameters.Add("clipId", SqlDbType.Int).Value = clipId;
				reader = command.ExecuteReader();

				if (reader.HasRows)
				{
					reader.Read();

					result = new Clip()
					{
						Id = reader.GetInt32(0),
						Title = reader.GetString(1),
						Author = reader.GetString(2),
						TotalTime = reader.GetInt32(3),
						OnAirDate = reader.GetDateTime(4),
						Url = reader.GetString(5)
					};
				}
			}
			catch (NullReferenceException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = null;
			}
			catch (SqlException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = null;
			}
			catch (InvalidOperationException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = null;
			}
			catch (IndexOutOfRangeException ex)
			{
				MvePublicService.ErrorHandler.LogMessage(ex.Message, false);
				result = null;
			}
			finally
			{
				command.Dispose();
				if (reader != null)
				{
					reader.Close();
					reader.Dispose();
				}
			}

			return result;
		}//end:LoadClipFromDatabase
	}
}
